package com.jason.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName WebConfig
 * @Description WebConfig
 * @Author Jason
 * @Date 2019/1/3 11:39
 * @Version 1.0
 **/
@Configuration
@EnableConfigurationProperties({CustomWebProperties.class})
public class WebConfig implements WebMvcConfigurer {

//    @Autowired
    private final CustomWebProperties properties;

    public WebConfig(CustomWebProperties properties) {
        this.properties = properties;
    }

    /**
     *
     * <p> 配置全局跨域问题 </p>
     * @Param [registry]
     * @return void
     * @date
     * @author Jason
     **/
    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConf = new CorsConfiguration();
        corsConf.addAllowedOrigin("*");
        corsConf.addAllowedHeader("*");
        corsConf.addAllowedMethod("*");
        corsConf.setAllowCredentials(true);
        corsConf.setMaxAge(3600L);
        return corsConf;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("properties: " + this.properties.getEnableJwtValidation());
        if (this.properties.getEnableJwtValidation()){
            registry.addInterceptor(new JwtHandlerInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/user/launcher", "/user/registry","/error");
        }
    }


}
